package com.adminsystem.java.config;

import com.adminsystem.java.common.Result;
import com.adminsystem.java.common.ResultCode;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author wangpeiao
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        return Result.fail(500, "系统异常: " + e.getMessage());
    }

    /**
     * 处理 POST 请求中 @Valid 校验失败的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        StringBuilder errorMessage = new StringBuilder("参数校验失败:");

        for (ObjectError error : errors) {
            errorMessage.append("\n").append(error.getDefaultMessage());
        }

        // 返回自定义错误码和消息
        return Result.fail(ResultCode.VALIDATE_FAILED, errorMessage.toString());
    }
}
